//
//  HRBDateSelectView.m
//  mjkjYG
//
//  Created by SZJ on 2020/4/8.
//  Copyright © 2020 SZJ. All rights reserved.
//

#import "HRBDateSelectView.h"
#import "NSDate+XLsn0w.h"


#define YearEq self.normalDate.year == self.currentDate.year
#define MonthEq (self.normalDate.year == self.currentDate.year && self.normalDate.month == self.currentDate.month)

@interface HRBDateSelectView()<UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic,strong) NSDateFormatter * dateFormatter;

@property (weak, nonatomic) IBOutlet UIPickerView *pickeView;

@property (nonatomic,assign) HRBDateSelectType type;

@property (nonatomic,strong) NSDate * normalDate;

@property (nonatomic,strong) NSDate * currentDate;

@property (nonatomic,strong) NSMutableArray <NSNumber *> * selectArr;

@property (nonatomic,copy) NSString * dateFormatString;


@property (nonatomic,assign) NSInteger normalYear;
@property (nonatomic,assign) NSInteger normalMonth;
@property (nonatomic,assign) NSInteger normalDay;
@end

@implementation HRBDateSelectView

/*
 时间这块  获取当前时间的时候 就 转成正常时间了
 */
NSDate *HRBTrueDate(NSDate *date){
    // 获得系统时区
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger interval = [zone secondsFromGMTForDate: date];
    //返回以当前NSDate对象为基准，偏移多少秒后得到的新NSDate对象
    NSDate *localeDate = [date dateByAddingTimeInterval: interval];
    return localeDate;
}

+ (HRBDateSelectView *(^)(HRBDateSelectType type))showForType{
    HRBDateSelectView *(^r)(HRBDateSelectType type) = ^(HRBDateSelectType type){
        HRBDateSelectView *selectView = [NSBundle.mainBundle loadNibNamed:@"HRBDateSelectView" owner:nil options:nil].firstObject;
        selectView.type = type;
        selectView.frame = UIScreen.mainScreen.bounds;
        [UIApplication.sharedApplication.keyWindow addSubview:selectView];
        return selectView;
    };
    return r;
}

-(HRBDateSelectView * _Nonnull (^)(NSString * _Nonnull))formatString{
    HRBDateSelectView * _Nonnull (^r)(NSString * _Nonnull) = ^(NSString *formatString){
        self.dateFormatString = formatString;
        return self;
    };
    return r;
}

-(void)awakeFromNib{
    [super awakeFromNib];
    self.pickeView.delegate = self;
    self.pickeView.dataSource = self;
    self.normalDate = HRBTrueDate(NSDate.date);
    self.currentDate = HRBTrueDate(NSDate.date);
  
    
    self.selectArr = @[@0,@0,@0,@0,@0,@0].mutableCopy;
}

-(void)setType:(HRBDateSelectType)type{
    _type = type;
    NSString *str = [self.dateFormatter stringFromDate:self.currentDate];
    NSArray <NSString *> *arr = [str componentsSeparatedByString:@"-"];

    self.normalYear = arr[0].integerValue;
    self.normalMonth = arr[1].integerValue;
    self.normalDay = arr[2].integerValue;
    [self begin];
}

- (void)begin{
    if (self.type == HRBDateSelectTypeEarly) {
        NSInteger month = [self getTimeDataForIndex:1] - 1;
        [self.pickeView selectRow:month inComponent:1 animated:YES];
        [self.selectArr replaceObjectAtIndex:1 withObject:@(month)];
        NSInteger day = [self getTimeDataForIndex:2] - 1;
        [self.pickeView selectRow:day inComponent:2 animated:YES];
        [self.selectArr replaceObjectAtIndex:2 withObject:@(day)];
    }
    if (self.type == HRBDateSelectTypeAfter_YMD) {
        [self.pickeView selectRow:0 inComponent:0 animated:YES];
        [self.pickeView selectRow:0 inComponent:1 animated:YES];
        [self.pickeView selectRow:0 inComponent:2 animated:YES];
    }
    if (self.type == HRBDateSelectTypeYMD) {
        NSInteger year = [self getTimeDataForIndex:0] - 1;
        [self.pickeView selectRow:year inComponent:0 animated:YES];
        [self.selectArr replaceObjectAtIndex:0 withObject:@(year)];
        NSInteger month = [self getTimeDataForIndex:1] - 1;
        [self.pickeView selectRow:month inComponent:1 animated:YES];
        [self.selectArr replaceObjectAtIndex:1 withObject:@(month)];
        NSInteger day = [self getTimeDataForIndex:2] - 1;
        [self.pickeView selectRow:day inComponent:2 animated:YES];
        [self.selectArr replaceObjectAtIndex:2 withObject:@(day)];
    }
    if (self.type == HRBDateSelectTypeHM) {
        NSInteger hour = [self getTimeDataForIndex:3];
        [self.pickeView selectRow:hour inComponent:0 animated:YES];
        [self.selectArr replaceObjectAtIndex:0 withObject:@(hour)];
        NSInteger day = [self getTimeDataForIndex:4];
        [self.pickeView selectRow:day inComponent:1 animated:YES];
        [self.selectArr replaceObjectAtIndex:1 withObject:@(day)];
    }
    if (self.type == HRBDateSelectTypeYMD_HM) {
        NSInteger year = [self getTimeDataForIndex:0] - 1;
        [self.pickeView selectRow:year inComponent:0 animated:YES];
        [self.selectArr replaceObjectAtIndex:0 withObject:@(year)];
        NSInteger month = [self getTimeDataForIndex:1] - 1;
        [self.pickeView selectRow:month inComponent:1 animated:YES];
        [self.selectArr replaceObjectAtIndex:1 withObject:@(month)];
        NSInteger day = [self getTimeDataForIndex:2] - 1;
        [self.pickeView selectRow:day inComponent:2 animated:YES];
        [self.selectArr replaceObjectAtIndex:2 withObject:@(day)];
        NSInteger hour = [self getTimeDataForIndex:3];
        [self.pickeView selectRow:hour inComponent:3 animated:YES];
        [self.selectArr replaceObjectAtIndex:3 withObject:@(hour)];
        NSInteger min = [self getTimeDataForIndex:4];
        [self.pickeView selectRow:min inComponent:4 animated:YES];
        [self.selectArr replaceObjectAtIndex:4 withObject:@(min)];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    if (self.type == HRBDateSelectTypeEarly) {
        return 3;
    }
    if (self.type == HRBDateSelectTypeYMD) {
        return 3;
    }
    if (self.type == HRBDateSelectTypeHM) {
        return 2;
    }
    if (self.type == HRBDateSelectTypeYMD_HM) {
        return 5;
    }
    if (self.type == HRBDateSelectTypeAfter_YMD) {
        return 3;
    }
    return 0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSArray <NSString *>*arr = [self getTimeDataArr];
    if (self.type == HRBDateSelectTypeEarly) {
        if (component == 0) return self.normalYear;
        if (component == 1) return 12;
        if (component == 2) return [self daysForCount:arr[0].intValue month:arr[1].intValue];
    }
    if (self.type == HRBDateSelectTypeYMD) {
        if (component == 0) return 10000;
        if (component == 1) return 12;
        if (component == 2) return [self daysForCount:arr[0].intValue month:arr[1].intValue];
    }
    if (self.type == HRBDateSelectTypeHM) {
        if (component == 0) return 24;
        if (component == 1) return 60;
        
    }
    if (self.type == HRBDateSelectTypeYMD_HM) {
        if (component == 0) return 10000;
        if (component == 1) return 12;
        if (component == 2) return [self daysForCount:arr[0].intValue month:arr[1].intValue];
        if (component == 3) return 24;
        if (component == 4) return 60;
    }
    if (self.type == HRBDateSelectTypeAfter_YMD) {
        if (component == 0) return 10000 - self.normalYear;
        if (component == 1) return self.currentDate.year == self.normalYear ? 12 - self.normalMonth + 1 : 12;
        if (component == 2) return [self daysForCount:arr[0].intValue month:arr[1].intValue];
    }
    return 0;
}




- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    
    for(UIView *singleLine in pickerView.subviews)
    {
        if (singleLine.frame.size.height < 1)
        {
            singleLine.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
        }
        
    }
    
    
    UILabel *genderLabel = [UILabel new];
    genderLabel.font = [UIFont systemFontOfSize:13];
    genderLabel.textColor = [UIColor colorWithRed:158/255.0 green:158/255.0 blue:158/255.0 alpha:1];
    genderLabel.textAlignment = NSTextAlignmentCenter;
    BOOL isSelect = self.selectArr[component].integerValue == row;
    if(isSelect){
        genderLabel.attributedText = [self pickerView:pickerView attributedTitleForRow:row forComponent:component];
    }else{
        genderLabel.text = [self getTitleForRow:row forComponent:component];
    }
    
    return genderLabel;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    [self.selectArr replaceObjectAtIndex:component withObject:@(row)];
    [self detailDate:component withNum:row];
    [pickerView reloadAllComponents];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.type == HRBDateSelectTypeAfter_YMD){
            NSArray <NSString *>*arr = [self getTimeDataArr];
            long year = arr[0].intValue - self.normalYear;
            [self.pickeView selectRow:year inComponent:0 animated:NO];
            [self.selectArr replaceObjectAtIndex:0 withObject:@(year)];
            long month = (arr[0].intValue == self.normalYear) ? arr[1].intValue - self.normalMonth : arr[1].intValue - 1;
            month = MAX(month, 0);
            [self.pickeView selectRow:month inComponent:1 animated:NO];
            [self.selectArr replaceObjectAtIndex:1 withObject:@(month)];
            long day = (arr[0].intValue == self.normalYear && arr[1].intValue == self.normalMonth) ? arr[2].intValue - self.normalDay : arr[2].intValue - 1;
            day = MAX(day, 0);
            NSInteger aDay = [self daysForCount:arr[0].intValue month:arr[1].intValue];
            day = MIN(aDay, day);
            [self.pickeView selectRow:day inComponent:2 animated:NO];
            [self.selectArr replaceObjectAtIndex:2 withObject:@(day)];
        }
        [pickerView reloadAllComponents];
    });
}

-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    if (self.type == HRBDateSelectTypeEarly) {
        return WIDTH_SCREEN / 3;
    }
    if (self.type == HRBDateSelectTypeYMD) {
        return WIDTH_SCREEN / 3;
    }
    if (self.type == HRBDateSelectTypeHM) {
        return WIDTH_SCREEN/ 2;
    }
    if (self.type == HRBDateSelectTypeYMD_HM) {
        return WIDTH_SCREEN/ 5;
    }
    if (self.type == HRBDateSelectTypeAfter_YMD) {
        return WIDTH_SCREEN/ 3;
    }
    return 0.f;
}



- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *titleString = [self getTitleForRow:row forComponent:component];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:titleString];
    
    [attributedString setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor colorWithRed:33/255.0 green:140/255.0 blue:250/255.0 alpha:1]} range:NSMakeRange(0, titleString.length)];
    return attributedString;
}

- (NSString *)getTitleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *titleString = @"";
    NSArray <NSString *>*arr = [self getTimeDataArr];
    if (self.type == HRBDateSelectTypeEarly){
        if (component == 0) titleString = [NSString stringWithFormat:@"%ld年", self.normalYear - row];
        if (component == 1) titleString = [NSString stringWithFormat:@"%ld月", row + 1];
        if (component == 2) titleString = [NSString stringWithFormat:@"%ld日", row + 1];
    }
    if (self.type == HRBDateSelectTypeYMD){
        if (component == 0) titleString = [NSString stringWithFormat:@"%ld年", row + 1];
        if (component == 1) titleString = [NSString stringWithFormat:@"%ld月", row + 1];
        if (component == 2) titleString = [NSString stringWithFormat:@"%ld日", row + 1];
    }
    if (self.type == HRBDateSelectTypeHM){
        if (component == 0) titleString = [NSString stringWithFormat:@"%ld时", row];
        if (component == 1) titleString = [NSString stringWithFormat:@"%ld分", row];
    }
    if (self.type == HRBDateSelectTypeYMD_HM){
        if (component == 0) titleString = [NSString stringWithFormat:@"%ld年", row + 1];
        if (component == 1) titleString = [NSString stringWithFormat:@"%ld月", row + 1];
        if (component == 2) titleString = [NSString stringWithFormat:@"%ld日", row + 1];
        if (component == 3) titleString = [NSString stringWithFormat:@"%ld时", row];
        if (component == 4) titleString = [NSString stringWithFormat:@"%ld分", row];
    }
    if (self.type == HRBDateSelectTypeAfter_YMD) {
        if (component == 0) titleString = [NSString stringWithFormat:@"%ld年", row + self.normalYear];
        if (component == 1) titleString = [NSString stringWithFormat:@"%ld月", arr[0].intValue == self.normalYear ? row + self.normalMonth : row + 1];
        if (component == 2) titleString = [NSString stringWithFormat:@"%ld日", (arr[0].intValue == self.normalYear && arr[1].intValue == self.normalMonth) ? row + self.normalDay :row + 1];
    }
    return titleString;
}

- (NSInteger)daysForCount:(NSInteger )year month:(NSInteger )month{
    NSArray <NSNumber *> *days = @[@0,@31,@28,@31,@30,@31,@30,@31,@31,@30,@31,@30,@31];
    NSInteger dayCounts = 0;
    if (month == 2) {
        if(((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))))
        {
            dayCounts = 29;
        }
    }
    
    dayCounts = days[month].integerValue;
    if (self.type == HRBDateSelectTypeAfter_YMD) {
        if (year == self.normalYear && month == self.normalMonth) {
            dayCounts = dayCounts - self.normalDay + 1;
        }
    }
    return  dayCounts;
}
- (NSInteger)daysForAll:(NSInteger )year month:(NSInteger )month{
    NSArray <NSNumber *> *days = @[@0,@31,@28,@31,@30,@31,@30,@31,@31,@30,@31,@30,@31];
    NSInteger dayCounts = 0;
    if (month == 2) {
        if(((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))))
        {
            dayCounts = 29;
        }
    }
    
    dayCounts = days[month].integerValue;
    return  dayCounts;
}
- (void)detailDate:(NSInteger)type withNum:(NSInteger)num{
    NSArray <NSString *>*arr = [self getTimeDataArr];
    
    NSInteger year = arr[0].intValue;
    NSInteger month = arr[1].intValue;
    NSInteger day = arr[2].intValue;
    NSInteger hour = arr[3].intValue;
    NSInteger min = arr[4].intValue;
    NSInteger sec = arr[5].intValue;
    
    if (self.type == HRBDateSelectTypeEarly) {
        if (type == 0) {
            NSInteger beginYear = self.normalYear;
            year = beginYear - num;
        }
        if (type == 1) month = num + 1;
        if (type == 2) day = num + 1;
        
    }
    if (self.type == HRBDateSelectTypeAfter_YMD) {
        

        if (type == 0){
            year = num + self.normalYear;
            month = (year == self.normalYear && month < self.normalMonth) ? self.normalMonth : month;
            day = (year == self.normalYear && month == self.normalMonth && day < self.normalDay) ? self.normalDay : day;
        }
        if (type == 1) {
            month =  arr[0].intValue == self.normalYear ? num + self.normalMonth : num + 1;
            day = (year == self.normalYear && month == self.normalMonth && day < self.normalDay) ? self.normalDay : day;
        }
        if (type == 2) day = (arr[0].intValue == self.normalYear && arr[1].intValue == self.normalMonth) ? num + self.normalDay : num + 1;
        
        
    }
    if (self.type == HRBDateSelectTypeYMD){
        if (type == 0) year = num + 1;
        if (type == 1) month = num + 1;
        if (type == 2) day = num + 1;
        
    }
    if (self.type == HRBDateSelectTypeHM){
        if (type == 0) hour = num;
        if (type == 1) min = num;
    }
    if (self.type == HRBDateSelectTypeYMD_HM) {
        if (type == 0) year = num + 1;
        if (type == 1) month = num + 1;
        if (type == 2) day = num + 1;
        if (type == 3) hour = num;
        if (type == 4) min = num;
    }
    
    NSInteger aDay = [self daysForAll:year month:month];
    if (self.type ==  HRBDateSelectTypeAfter_YMD && (arr[0].intValue == self.normalYear && arr[1].intValue == self.normalMonth && day < self.normalDay)){
        day = self.normalDay;
    }
    
    if (day > aDay) {
        day = aDay;
        [self.pickeView selectRow:day - 1 inComponent:2 animated:NO];
    }

    self.currentDate = [self.dateFormatter dateFromString:[NSString stringWithFormat:@"%ld-%ld-%ld- %ld-%ld-%ld",year,month,day,hour,min,sec]];
    
}
/*
 获取当前时间的第几个数据
 */
- (NSInteger)getTimeDataForIndex:(NSInteger)index{
    NSString *str = [self.dateFormatter stringFromDate:self.currentDate];
    NSArray <NSString *> *arr = [str componentsSeparatedByString:@"-"];
    return arr[index].integerValue;
}

/*
 获取当前选中时间字符串的数组
 */
- (NSArray *)getTimeDataArr{
    NSString *str = [self.dateFormatter stringFromDate:self.currentDate];
    NSArray <NSString *> *arr = [str componentsSeparatedByString:@"-"];
    return arr;
}




- (IBAction)cale:(UIButton *)sender {
    [self removeFromSuperview];
}

- (IBAction)sure:(UIButton *)sender {
    
    if (self.result) {
        NSDateFormatter *f = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
        [f setTimeZone:timeZone];
        [f setDateFormat:self.dateFormatString];
        self.result([f stringFromDate:self.currentDate],self.currentDate);
    }
    
    [self removeFromSuperview];
}

-(NSDateFormatter *)dateFormatter{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
        [_dateFormatter setTimeZone:timeZone];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd-HH-mm-ss"];
    }
    return _dateFormatter;
}
+ (BOOL)checkTime:(NSTimeInterval)beginTime endTime:(NSTimeInterval)endTime needCompareToToday:(BOOL)compare{
    
    NSTimeInterval time = NSDate.date.timeIntervalSince1970;
    if (compare) {
        if (beginTime > time || endTime > time) {
            [CCToast showMessage:@"不能晚于今天"];
            return NO;
        }
    }
    if (beginTime == 0 || endTime == 0) {
        return YES;
    }
    if (beginTime > endTime) {
        [CCToast showMessage:@"结束时间不能小于开始时间"];
        return NO;
    }
    return YES;
}
@end
